<?php
	require_once $_SERVER['DOCUMENT_ROOT'] . '/SAGER/logic/factory/CommandFactory.php';
	
	error_reporting (E_ALL ^ E_NOTICE);
	
	$debug = $_SESSION['debug'];
	

	class PresenterOrder {
		/**
		 * Constructor of the presenter
		 */
		public function __construct() {}		

		/**
		 * Method to execute when user clicks on creating a new PurchaseOrder
		 */
		public function clickCreateOrder($order,$orderType)  {
			$address = explode(", ", $order['address']);
			$country = $address[3];
			$stateProvince = $address[2];
			$city = $address[1];
			$zone = $address[0];
				
		$GLOBALS['debug'] -> log($address, "Presentador campo direccion Purchase Order");

			$phones = explode("\n", $order['phones']);
			$firstPhone = explode(": ", $phones[0]);
			$homePhone = $firstPhone[1];		
			$secondPhone = explode(": ", $phones[1]);
			$mobilePhone = $secondPhone[1];		
			$thirdPhone = explode(": ", $phones[2]);
			$workPhone = $thirdPhone[1];
			$fourthPhone = explode(": ", $phones[3]);
			$faxPhone = $fourthPhone[1];
			
		$GLOBALS['debug'] -> log($phones, "Presentador campo phone Purchase Order");	

			$productsTextarea = explode("\n", $order['products']);
			for ($i = 0; $i < count($productsTextarea); $i++) {
				$productFeatures = explode(", ", $productsTextarea[$i]);
				$products['pk_line'][$i] = $i + 1;
				$productUnitsQuantity = explode(" ", $productFeatures[2]);
				$products['quantity'][$i] = $productUnitsQuantity[0];
				$products['units'][$i] = $productUnitsQuantity[1];
				$productUnitCost = explode(' ', substr($productFeatures[3], 4));
				$products['unit_cost'][$i] = $productUnitCost[0];
				$products['purchase_order_number'][$i] = $order['number'];
				$products['purchase_order_control_number'][$i] = $order['controlNumber'];
				$products['pk_code'][$i] = substr($productFeatures[0], 6);
				$products['branch_rif'][$i] = 'J-31099802-1';
			}
			$GLOBALS['debug'] -> log( "Presentador campos para el comando Purchase Order");	
			$GLOBALS['debug'] -> log($order, "Presentador campos purchase Order number");			
			
			$command = CommandFactory :: createCommandCreateOrder($order['ciRifList'], 
				$order['ciRif'], $order['clientName'], $order['secondName'], 
				$order['firstLastName'], $order['secondLastName'], $order['emailAddress'], 
				date("Y-m-d", time()), '', $country, $stateProvince, $city, $zone, $homePhone,
				$mobilePhone, $workPhone, $faxPhone, $order['number'], $order['controlNumber'], 
				$order['orderDate'], $order['tax'],'NO LEIDO' ,$products,$orderType);
			$command -> execute();
			$GLOBALS['debug'] -> log($command -> getResult(), "result");		
			return $command -> getResult();
		}
		
		/**
		 * Method to execute to select requests
		 */
		public function selectRequests($order) {
			$command = CommandFactory :: createCommandSelectRequests($order);
			$command -> execute();
			$requests = $command -> getResult();
			
			$result = '<table class="formTable" cellspacing="0" cellpadding="5">';
			$result .= '<tr class="odd">';
			$result .= '<td align="center"><b>N&uacute;mero</b></td>';
			$result .= '<td align="center"><b>N&uacute;mero de control</b></td>';
			$result .= '<td align="center"><b>Fecha</b></td>';
			$result .= '<td align="center"><b>Tasa de impuestos</b></td>';
			$result .= '<td align="center"><b>Cliente</b></td>';
			$result .= '<td align="center"><b>Detalles</b></td>';
			$result .= '</tr>';
			$i = 0; $unread = 0;
			while ($i < count($requests['pk_number'])) {
				if ($i % 2 == 0) $result .= '<tr class="even">';
				else $result .= '<tr class="odd">';
				
				if (strcmp($requests['read_status'][$i], 'NO LEIDO') == 0) {
					$unread++;
					$result .= '<b>';
				}
								
				$result .= '<td align="center">' . $requests['pk_number'][$i] . '</td>';
				$result .= '<td align="center">' . $requests['pk_control_number'][$i] . '</td>';
				$result .= '<td align="center">' . $requests['date'][$i] . '</td>';
				$result .= '<td align="center">' . $requests['tax'][$i] . '%</td>';
				$result .= '<td align="center">' . $requests['client'][$i] . '</td>';
				$result .= '<td align="center"><a href="#" onclick="xajax_selectRequestDetails(' . $requests['pk_number'][$i] . ', ' . $requests['pk_control_number'][$i] . ')">Ver</a></td>';
				
				if (strcmp($requests['read_status'][$i++], 'NO LEIDO') == 0)
					$result .= '</b>';
				
				$result .= '</tr>';
			}
			
			$result .= '</table>#separator#' . $unread;
			
			return $result;
		}
		
		/**
		 * Method to execute to select given request details
		 */
		public function selectRequestDetails($number, $controlNumber) {
			$command = CommandFactory :: createCommandSelectRequestDetails
				($number, $controlNumber);
			$command -> execute();
			$products = $command -> getResult();
			
					
		    $GLOBALS['debug']->log($controlNumber,'Numero de control');
			
			$result = '<table class="formTable" cellspacing="0" cellpadding="5">';
			$result .= '<tr class="odd">';
			$result .= '<td align="center"><b>Rengl&oacute;n</b></td>';
			$result .= '<td align="center"><b>Descripci&oacute;n</b></td>';
			$result .= '<td align="center"><b>Unidades</b></td>';
			$result .= '<td align="center"><b>Cantidad</b></td>';
			$result .= '<td align="center"><b>Costo unitario</b></td>';
			$result .= '<td align="center"><b>Total</b></td>';
			$result .= '</tr>';
			$i = 0; $subtotal = 0;
			while ($i < count($products['pk_line'])) {
				if ($i % 2 == 0) $result .= '<tr class="even">';
				else $result .= '<tr class="odd">';
					
				$subtotal += $products['total'][$i];
				
				$result .= '<td align="center">' . $products['pk_line'][$i] . '</td>';
				$result .= '<td align="center">' . $products['name'][$i] . '</td>';
				$result .= '<td align="center">' . $products['units'][$i] . '</td>';
				$result .= '<td align="center">' . $products['quantity'][$i] . '</td>';
				$result .= '<td align="center">' . $products['unit_cost'][$i] . '</td>';
				$result .= '<td align="center">' .  $products['total'][$i++] . '</td>';
				
				$result .= '</tr>';
			}
			
			if ($i % 2 == 0) $result .= '<tr class="even">';
			else $result .= '<tr class="odd">';			
			$result .= '<td colspan="5" align="right">Subtotal</td>';
			$result .= '<td align="center">' . $subtotal . '</td>';
			$result .= '</tr>'; $i++;
			
			if ($i % 2 == 0) $result .= '<tr class="even">';
			else $result .= '<tr class="odd">';	
			$result .= '<td colspan="5" align="right">' . $products['tax'][0] . '% IVA</td>';
			$result .= '<td align="center">' . $subtotal * ($products['tax'][0] / 100) . '</td>';
			$result .= '</tr>'; $i++;
			
			if ($i % 2 == 0) $result .= '<tr class="even">';
			else $result .= '<tr class="odd">';			
			$result .= '<td colspan="5" align="right">Total</td>';
			$result .= '<td align="center">' . $subtotal * (1 + $products['tax'][0] / 100) . '</td>';
			$result .= '</tr>';
			
			$result .= '</table><br />';
			
			$result .= '<div align="center">';
			$result .= '<a href="#" 
				onclick="xajax_selectRequests(document.form_watch.order.value)">Regresar</a>';
			$result .= '</div>';
			
			
			return $result;
		}
		
		/**
		 * Method to execute to load all existing products
		 */
		public function loadExistingProducts() {
			$command = CommandFactory :: createCommandSelectProducts();
			$command -> execute();
			$products = $command -> getResult();
			
			$result = '<select name="product" onchange="xajax_updateProductFeatures(document.purchaseOrderProducts.product.options[document.purchaseOrderProducts.product.selectedIndex].value)">';
			$result .= '<option value="0">Seleccione un producto</option>';
			$i = 0;
			
			while ($i < count($products['pk_code'])) {
				$result .= '<option value="' . $products['pk_code'][$i] . '">' . 
					$products['name'][$i];
				
				if (strcmp($products['specifications'][$i], '') != 0) {
					$result .= '&nbsp;(' . $products['specifications'][$i] . 
						')</option>';
				}
				
				$i++;
			}
			
			$result .= '</select>';
			
			return $result;
		}
		
		/**
		 * Method to execute to update product features
		 */
		public function updateProductFeatures($pkCode) {
			$command = CommandFactory :: createCommandSelectProductByCode($pkCode);
			$command -> execute();
			$product = $command -> getResult();
			
			$result = '<input type="hidden" id="productName" value="' . $product['name'][0] . '" />';
			$result .= '<input type="text" id="quantity" size="8" maxlength="8" value="0" onblur="updateTotalCost(document.purchaseOrderProducts.quantity.value, document.purchaseOrderProducts.unitCost.value)" />&nbsp;';
			$result .= '<input name="productUnits" size="8" maxlength="8" readonly="readonly" 
				value="' . $product['product_units'][0] . '" />&nbsp;';
			$result .= '<input type="button" name="buttonAddProduct" value="Agregar" 
				onclick="addProduct(
document.purchaseOrderProducts.product.options[document.purchaseOrderProducts.product.selectedIndex].value,
document.purchaseOrderProducts.productName.value,
document.purchaseOrderProducts.quantity.value, document.purchaseOrderProducts.productUnits.value, 
document.purchaseOrderProducts.unitCost.value, document.purchaseOrderProducts.unitCostCurrency.value)" />#separator#';
			$result .= '<input type="text" id="unitCost" size="8" maxlength="15" 
				readonly="readonly" value="' . $product['unit_cost'][0] . '" />&nbsp;';
			$result .= '<input type="text" id="unitCostCurrency" size="8" maxlength="20" 
				readonly="readonly" value="' . $product['unit_cost_currency'][0] . 
				'" />#separator#';
			$result .= '<input type="text" id="totalCost" size="8" maxlength="15" 
				readonly="readonly" value="0" />&nbsp;';
			$result .= '<input type="text" id="totalCostCurrency" size="8" maxlength="20" 
				readonly="readonly" value="' . $product['unit_cost_currency'][0] . 
				'" />';
				
			return $result;
		}
		
		/**
		 * Method to execute to select an existing client
		 */
		public function selectExistingClient($clientType, $ciRif) {
			if (strcmp($clientType, 'ci') == 0)
				$command = CommandFactory :: createCommandSelectExistingNaturalCustomer($ciRif);
			
			else
				$command = CommandFactory :: createCommandSelectExistingLegalClient($ciRif);
			
			$command -> execute();
			$result = $command -> getResult();
			
			if (strcmp($result['name'], '') != 0) {			
				$client = '<input type="text" name="clientName" size="32" maxlength="30" 
					value="' . $result['name'] . '" />#separator#';
				$client .= '<input type="text" id="secondName" name="secondName" size="32" 
					maxlength="20" value="' . $result['second_name'] . '" />#separator#';
				$client .= '<input type="text" id="firstLastName" name="firstLastName" size="32" 
					maxlength="20" value="' . $result['first_last_name'] . '" />#separator#';
				$client .= '<input type="text" id="secondLastName" name="secondLastName" 
					size="32" maxlength="20" value="' . $result['second_last_name'] . '" />
					#separator#';
				$client .= '<input type="text" name="emailAddress" size="32" maxlength="40" 
					value="' . $result['email_address'] . '" />';
					
				return $client;
			}
		}
	}
?>